package com.cgy.wodeyigui.product.exception;


import com.cgy.common.exception.BizCodeException;
import com.cgy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
//@ResponseBody //返回json数据
//@ControllerAdvice(basePackages ="com.cgy.wodeyigui.product.controller" )全局捕捉异常
@RestControllerAdvice(basePackages ="com.cgy.wodeyigui.product.controller" )//@ResponseBody和@ControllerAdvice的结合
public class YiguiExceptionControllerAdvice {
    /*
            集中数据校验异常
     */
    //为空时进入该异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)//注解告诉mvc能处理哪些异常类,必须与value的值相通才会进入该方法
    public R bandleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String ,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError -> {
        errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        }));
        return R.error(BizCodeException.VAILD_EXCEPTION.getCode(),"数据校验出现问题").put("data",errorMap);
    }
    //全局异常
    @ExceptionHandler(value = Throwable.class)
   public R handleEcxeption(Throwable Throwable){

        return R.error(BizCodeException.UNKNOW_EXCEPTION.getCode(), BizCodeException.UNKNOW_EXCEPTION.getMessage());
   }

}
